//package com.fingard.dsp.bank.directbank.ccb04;
//
//import com.fingard.FGBiz;
//import com.fingard.constant.Format;
//import com.fingard.db.JDBCHelper;
//import com.fingard.dsp.bank.directConfig.NodeSalaryItem;
//import com.fingard.dsp.bank.directConfig.SalaryConfig;
//import com.fingard.dsp.bank.directbank.bankInterface.IWithhold;
//import com.fingard.dsp.bank.directbank.ccb04.util.Des3;
//import com.fingard.dsp.bank.directbank.ccb04.util.RSAHelper;
//import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
//import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
//import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
//import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
//import com.fingard.dsp.salaryset.SalaryDecrypt;
//import com.fingard.io.FileHelper;
//import com.fingard.text.Base64Helper;
//import com.fingard.text.StringHelper;
//import com.fingard.util.RSAEncryptHelper;
//import com.fingard.xml.XmlTextReader;
//import com.fingard.xml.XmlTextWriter;
//import org.bouncycastle.util.encoders.Base64;
//
//import java.io.File;
//import java.math.BigDecimal;
//import java.net.URLEncoder;
//import java.sql.Connection;
//import java.util.*;
//
///**
// * @Description TODO
// * @Author xtt
// * @Date 2019-10-08$ 10:00$
// **/
//public class CCB04Withhold extends CCB04Base implements IWithhold {
//    private static final String INSERTRECEIPT = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,REQSEQID,RESERVE1) values (?,?,?,?);";
//    private static final String SELECTRECEIPT = "SELECT RESERVE1 FROM REQSEQIDMAPPING WHERE REQSEQID=? AND BANKCODE=?;";
//
//    @Override
//    public RetAtsBatPayRec d_9208_singlePay(ReqBatPayRec p_req9188) throws Exception {
//        return d_PayRec(p_req9188);
//    }
//
//    @Override
//    public RetAtsQryBatPayRec d_9244_QrySinglePay(ReqQryBatPayRec p_req9244) throws Exception {
//        return null;
//    }
//
//    /**
//     * 参考接口：P1CLP1051 代发代扣直联交易申请
//     * <p>
//     * 批次提交：一个批量文件中记录数不要超过5000笔
//     *
//     * @param p_reqBat
//     * @return
//     * @throws Exception
//     */
//    public RetAtsBatPayRec d_PayRec(ReqBatPayRec p_reqBat) throws Exception {
//        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
//        retAts.reqSeqID = p_reqBat.reqBatchNO;
//        String enableSalaryDecrypt = getBankConfig().getValueAsString("enableSalaryDecrypt");
//        String commedTypeArrs = getBankConfig().getValueAsString("salaryDecryptCommand");
//        if ("true".equals(enableSalaryDecrypt) && StringHelper.hasAnyChar(commedTypeArrs)) {
//            String[] arrs = commedTypeArrs.split(",");
//            List<String> list = Arrays.asList(arrs);
//            if (list.contains(p_reqBat.reqHeader.commandCode)) {
//                if (StringHelper.isNullOrEmpty(p_reqBat.decryptKey)) {
//                    throw new Exception("获取密钥失败");
//                }
//                p_reqBat.decryptKey = RSAEncryptHelper.base64PlusRSADecryptAndUncompress(p_reqBat.decryptKey, "utf-8", SalaryDecrypt.rsaPrivateKey);
//                p_reqBat.isNeedDecrypt = true;
//                isNeedHiddleField = true;
//            }
//            //变换成真正的密钥
//            if (StringHelper.hasAnyChar(p_reqBat.decryptKey)) {
//                String key = p_reqBat.reqHeader.bankCode + "-" + p_reqBat.reqHeader.corporation
//                        + "-" + p_reqBat.reqHeader.group;
//                SalaryConfig salaryConfig = SalaryDecrypt.getSalaryConfig(key);
//                if (salaryConfig == null) {
//                    throw new Exception("获取渠道：" + key + " 的解密配置失败");
//                }
//                Map<String, NodeSalaryItem> map = salaryConfig.nodeSalaryItemMap;
//                p_reqBat.salaryItemMap = map;
//                if (map.keySet().contains("TotalAmount")) {
//                    NodeSalaryItem item = map.get("TotalAmount");
//                    String totalAmt = com.fingard.util.secret.salary.DESUtil.jdkDESDecryptMode(p_reqBat.totalAmt, p_reqBat.decryptKey);
//                    if (StringHelper.hasAnyChar(totalAmt)) {
//                        p_reqBat.totalAmt = totalAmt.split(item.union)[item.index - 1];
//                    }
//                }
//            }
//        }
//
//        getBnkToken();
//        StringBuilder FileContent = new StringBuilder();
//        FileContent.append(String.format("%s|%s|%s|%s|%s|%s|%s|%s|%s|\n", "序号", "账号", "户名", "金额", "跨行标志", "人民银行联行号", "多方协议号", "摘要", "备注"));
//        StringBuffer fileHiddenAmout = new StringBuffer();
//        if (isNeedHiddleField) {
//            fileHiddenAmout.append(String.format("%s|%s|%s|%s|%s|%s|%s|%s|%s|\n", "序号", "账号", "户名", "金额", "跨行标志", "人民银行联行号", "多方协议号", "摘要", "备注"));
//
//        }
//        int count = 0;
//        BigDecimal amount = BigDecimal.ZERO;
//
//        StringBuilder seqNoMappingContent = new StringBuilder();
//        while (p_reqBat.readRecord()) {
//            count++;
//
//            if (seqNoMappingContent.length() > 0) {
//                seqNoMappingContent.append("\r\n");
//            }
//
//            String postScript = count + "";
//            String oppAct = "";
//            String oppName = "";
//            String oppBankName = "";
//            if ("9288".equals(p_reqBat.reqHeader.transType) || "9208".equals(p_reqBat.reqHeader.transType)) {
//                oppAct = p_reqBat.readedDetail.recAct;
//                oppName = p_reqBat.readedDetail.recName;
//                oppBankName = p_reqBat.readedDetail.recBankName;
//            }
//            String payAmount = p_reqBat.readedDetail.payAmount;
//            amount = amount.add(BigDecimal.valueOf(Double.parseDouble(payAmount)));
////            String sameBnkFlag = oppBankName.contains("中国建设银行") ? "0" : "1";  // 0:同行  1：跨行
////            String sameBnkFlag = "1".equals(p_reqBat.readedDetail.sameBnk) ? "0" : "1";  // 0:同行  1：跨行
//            String sameBnkFlag = "0";//建行代扣暂不支持跨行
//            String cnapsCode = "";
//            if ("1".equals(sameBnkFlag)) { // 跨行
//                cnapsCode = p_reqBat.readedDetail.cnapsCode;
//            }
//            String multiProtocol = "";// 多方协议号(代扣时使用：值为签约缴费编号)
//            if ("9288".equals(p_reqBat.reqHeader.transType) || "9208".equals(p_reqBat.reqHeader.transType)) {
//                multiProtocol = p_reqBat.readedDetail.authCode;
//            }
//            String summary = p_reqBat.readedDetail.memo;// 摘要
//            String memo = p_reqBat.readedDetail.abstractATS;// 备注存入批次明细流水号，供批次明细查询时作为对账码返回ATS
//
//            FileContent.append(String.format("%s|%s|%s|%s|%s|%s|%s|%s|%s|\n", postScript, oppAct, oppName, payAmount, sameBnkFlag, cnapsCode, multiProtocol, summary, memo));
//            if (isNeedHiddleField) {
//                fileHiddenAmout.append(String.format("%s|%s|%s|%s|%s|%s|%s|%s|%s|\n", postScript, oppAct, oppName, "*****.**", sameBnkFlag, cnapsCode, multiProtocol, summary, memo));
//            }
//            seqNoMappingContent.append(p_reqBat.readedDetail.askNumber).append(",").append(memo);
//        }
//        if (isNeedHiddleField) {
//            WriteBankLogLn2("批次文件内容：\r\n" + fileHiddenAmout);
//        } else {
//            WriteBankLogLn2("批次文件内容：\r\n" + FileContent);
//        }
//
//        String BatchFileName = p_reqBat.reqBatchNO + ".txt";
//        String localUpFilePath = getTempFileDirectory() + File.separator + Format.Date8Format.format(p_reqBat.getPayDateTime()) + File.separator + BatchFileName;
//        WriteBankLogLn2("批次文件内容本地保存路径:\r\n" + localUpFilePath);
//        if (isNeedHiddleField) {
//            FileHelper.writeFile(localUpFilePath, fileHiddenAmout.toString(), getCharset());
//        } else {
//            FileHelper.writeFile(localUpFilePath, FileContent.toString(), getCharset());
//        }
//        Date tmpDateNow = new Date();
//        WriteBankLogLn2("本地流水映射文件内容:\r\n" + seqNoMappingContent.toString());
//        String tmpBatSeqNoPath = getDataFileDirectory(tmpDateNow) + File.separator + p_reqBat.reqBatchNO + ".txt";
//        WriteBankLogLn2("本地流水映射文件路径:" + tmpBatSeqNoPath);
//        FileHelper.writeFile(tmpBatSeqNoPath, seqNoMappingContent.toString(), getCharset());
//
//        //POST 参数 1: chanl_cust_no=电子银行合约编号
//        String chanl_cust_no = getBankConfig().getValueAsString("CustNo");
//
//        //POST 参数 2：filename=文件名（不含路径的文件名，DESede(3DES)对称密钥加密）
//        byte[] tmpName = Des3.encryptMode(Base64Helper.decode(bankFront.token), BatchFileName.getBytes("GBK"));
//        tmpName = Base64.encode(tmpName);
//        String filename = new String(tmpName);
//
//        //POST 参数 3：signature=数字签名（对文件名作的数字签名）
//        String priKey = FileHelper.readFileText(strtmpFile + chanl_cust_no + "_prikey.txt", getCharset());
//        String signature = RSAHelper.sign(new String(BatchFileName), priKey, getCharset());//MD5withRSA(batchFileName);
//
//        //POST 参数 4：data=文件内容（DESede(3DES)对称密钥加密）
//        byte[] tmpData = Des3.encryptMode(Base64Helper.decode(bankFront.token), FileContent.toString().getBytes("GBK"));
//        tmpData = Base64.encode(tmpData);
//        String data = new String(tmpData);
//
//        //POST 参数 5：dirflag=是否上传至子目录（0-否，1-是，DESede(3DES)对称密钥加密
//        byte[] tmpZero = Des3.encryptMode(Base64Helper.decode(bankFront.token), "0".getBytes("GBK"));
//        tmpZero = Base64.encode(tmpZero);
//        String dirflag = new String(tmpZero);
//
//        StringBuilder sb = new StringBuilder();
//        sb.append("chanl_cust_no=" + URLEncoder.encode(chanl_cust_no, "gbk"));
//        sb.append("&filename=" + URLEncoder.encode(filename, "gbk"));
//        sb.append("&signature=" + URLEncoder.encode(signature, "gbk"));
//        sb.append("&data=" + URLEncoder.encode(data, "gbk"));
//        sb.append("&dirflag=" + URLEncoder.encode(dirflag, "gbk"));
//
//        String[] PostRet = UploadFileByHttpPost(sb);
//
//        String BatchResult = IsBatchValid(PostRet[1]);
//
//        String BatchFileServerName = "";
//        Connection conn = FGBiz.getLocalDbConn();
//        if (!StringHelper.isNullOrEmpty(BatchResult)) {
//            String[] SplitedResult = BatchResult.split("\\|");
//            if ("SUCCESS".equals(SplitedResult[0])) {
//                BatchFileServerName = SplitedResult[3];
//                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//                //uuid bankcode  批次号/请求号  文件名
//                JDBCHelper.update(conn, INSERTRECEIPT, new Object[]{uuid, p_reqBat.reqHeader.bankCode, p_reqBat.reqHeader.reqSeqID, BatchFileServerName});
//                conn.close();
//            }
//        }
//
//        try {
//            //查询之前做登录操作 下载公钥密钥 进行3des加密 和md5withRSA签名 byte[]数据和String进行base64互转
//            getBnkToken();
////            if (triDesKeys != null && triDesKeys.length != 1024) {
//            if (StringHelper.hasAnyChar(bankFront.token)) {
//                if (new File(String.format("%1$s%2$s_BnkPubKey.txt", strtmpFile, bankFront.org)).exists()) {
//                    if (!"".equals(bankFront.loginFlag) && !"false".equals(bankFront.loginFlag)) {
//                        txCode = "P1CLP1051";
//                        reqSeqID = p_reqBat.reqBatchNO;
//                        XmlTextWriter xmlWriter = new XmlTextWriter();
//                        XmlTextWriter xmlWriterWithoutCDATA = new XmlTextWriter();
//                        writeCommonHeaderWithoutCDATA(xmlWriterWithoutCDATA);
//                        xmlWriterWithoutCDATA.writeStartElement("request");
//                        String CustNo = bankFront.org;
//                        xmlWriterWithoutCDATA.writeElementString("Txn_SN", p_reqBat.reqBatchNO);
//                        String projectID = "";
////                        if (p_reqBat.reqHeader.transType.equals("9208")) {
////                            projectID = getBankConfig().getSetValue("projectID", "", "9208");
////                        } else {
////                            projectID = getBankConfig().getSetValue("projectID", "", "9288");
////                        }
//                        String projectUseId = "";
////                        if ("9208".equals(p_reqBat.reqHeader.transType)) {
////                            projectUseId = "zlds00001";
////                        } else if ("9288".equals(p_reqBat.reqHeader.transType)) {
////                            projectUseId = "zlds00001";
////                        }
//                        HashMap<String, String> prjMap = getBankConfig().getMapAdvanceValues("prjMapping" + p_reqBat.reqHeader.transType, new String[]{"act"}, new String[]{"prjID", "useID"}, new String[]{p_reqBat.ownAct}, false);
//                        if (prjMap != null && prjMap.size() > 0) {
//
//                            if (prjMap.containsKey("prjID") && StringHelper.hasAnyChar(prjMap.get("prjID"))) {
//                                projectID = prjMap.get("prjID");
//                            }
//                            if (prjMap.containsKey("useID") && StringHelper.hasAnyChar(prjMap.get("useID"))) {
//                                projectUseId = prjMap.get("useID");
//                            }
//                        }
//                        xmlWriterWithoutCDATA.writeElementString("EBnk_SvAr_ID", CustNo);
//                        xmlWriterWithoutCDATA.writeElementString("Entrst_Prj_ID", projectID);
//                        xmlWriterWithoutCDATA.writeElementString("Prj_Use_ID", projectUseId);
//
//                        xmlWriterWithoutCDATA.writeElementString("EtrUnt_AccNo", p_reqBat.ownAct);
//                        String opertorID = "";
//                        if ("9208".equals(p_reqBat.reqHeader.transType)) {
//                            opertorID = getBankConfig().getSetValue("opertorID", "", "9208");
//                        } else if ("9288".equals(p_reqBat.reqHeader.transType)) {//"9208".equals(p_reqBat.reqHeader.transType)
//                            opertorID = getBankConfig().getSetValue("opertorID", "", "9288");
//                        }
//                        xmlWriterWithoutCDATA.writeElementString("TDP_ID", opertorID);
//                        xmlWriterWithoutCDATA.writeElementString("TDP_Nm", "");
//                        xmlWriterWithoutCDATA.writeElementString("CntprtAcc", "");
//                        xmlWriterWithoutCDATA.writeElementString("Cntrprt_AccNm", "");
//                        xmlWriterWithoutCDATA.writeElementString("IwBk_BrNo", "");
//                        xmlWriterWithoutCDATA.writeElementString("IwBk_BkNm", "");
//                        xmlWriterWithoutCDATA.writeElementString("MltltAgrm_No", "");
//                        xmlWriterWithoutCDATA.writeElementString("CCY_ID", "156");
//                        xmlWriterWithoutCDATA.writeElementString("Orig_File_Nm", BatchFileName);
//                        xmlWriterWithoutCDATA.writeElementString("SRP_TxnAmt", "");
//                        xmlWriterWithoutCDATA.writeElementString("SCSP_Smy_Dsc", "");
//                        xmlWriterWithoutCDATA.writeElementString("Rvw_Ind", "1");
//                        xmlWriterWithoutCDATA.writeElementString("TAmt", amount + "");
//                        xmlWriterWithoutCDATA.writeElementString("TDnum", p_reqBat.totalNum);
//                        xmlWriterWithoutCDATA.writeElementString("VCHR_TP_CODE", "1");//0-单笔 1-批量
//                        xmlWriterWithoutCDATA.writeElementString("Lng_Vrsn", "1");
//                        writeComEntityWithoutCDATA(xmlWriterWithoutCDATA);
//                        xmlWriterWithoutCDATA.writeStartElement("FILE_LIST_PACK");
//                        xmlWriterWithoutCDATA.writeElementString("FILE_NUM", "1");
//                        xmlWriterWithoutCDATA.writeStartElement("FILE_INFO");
//                        xmlWriterWithoutCDATA.writeElementString("FILE_NAME", BatchFileServerName);
//                        xmlWriterWithoutCDATA.writeElementString("Msg_Smy", md5(FileContent.toString(), "GBK"));//MD5
//                        xmlWriterWithoutCDATA.writeEndDocument();
//
//                        int n = xmlWriterWithoutCDATA.toXmlString().length();
//                        xmlLength = decimalFormat.format(n);
//
//                        writeCommonHeader(xmlWriter);
//                        xmlWriter.writeStartElement("request");
//
//                        txCode = "P1CLP1051";
//                        reqSeqID = p_reqBat.reqBatchNO;
//                        //写入通用的头部节点
//                        xmlWriter.writeStartElement("request");
//                        xmlWriter.writeElementCDATA("Txn_SN", p_reqBat.reqBatchNO);
//                        xmlWriter.writeElementCDATA("EBnk_SvAr_ID", CustNo);
//                        xmlWriter.writeElementCDATA("Entrst_Prj_ID", projectID);
//                        xmlWriter.writeElementCDATA("Prj_Use_ID", projectUseId);
//                        xmlWriter.writeElementCDATA("EtrUnt_AccNo", p_reqBat.ownAct);
//                        xmlWriter.writeElementCDATA("TDP_ID", opertorID);
//                        xmlWriter.writeElementCDATA("TDP_Nm", "");
//                        xmlWriter.writeElementCDATA("CntprtAcc", "");
//                        xmlWriter.writeElementCDATA("Cntrprt_AccNm", "");
//                        xmlWriter.writeElementCDATA("IwBk_BrNo", "");
//                        xmlWriter.writeElementCDATA("IwBk_BkNm", "");
//                        xmlWriter.writeElementCDATA("MltltAgrm_No", "");
//                        xmlWriter.writeElementCDATA("CCY_ID", "156");
//                        xmlWriter.writeElementCDATA("Orig_File_Nm", BatchFileName);
//                        xmlWriter.writeElementCDATA("SRP_TxnAmt", "");
//                        xmlWriter.writeElementCDATA("SCSP_Smy_Dsc", "");
//                        xmlWriter.writeElementCDATA("Rvw_Ind", "1");
//                        xmlWriter.writeElementCDATA("TAmt", amount + "");
//                        xmlWriter.writeElementCDATA("TDnum", p_reqBat.totalNum);
//                        xmlWriter.writeElementCDATA("VCHR_TP_CODE", "1");//0单笔，1批量
//                        xmlWriter.writeElementCDATA("Lng_Vrsn", "1");
//                        writeComEntity(xmlWriter);
//                        xmlWriter.writeStartElement("FILE_LIST_PACK");
//                        xmlWriter.writeElementCDATA("FILE_NUM", "1");
//                        xmlWriter.writeStartElement("FILE_INFO");
//                        xmlWriter.writeElementCDATA("FILE_NAME", BatchFileServerName);
//                        xmlWriter.writeElementCDATA("Msg_Smy", md5(FileContent.toString(), "GBK"));//MD5
//                        xmlWriter.writeEndDocument();
//                        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
//                        if (tmpStrRet[0].length() == 0) {
//                            StringBuilder msg = new StringBuilder();
//                            XmlTextReader tmpBkReader = getBankInfo(tmpStrRet[1], msg);
//                            String xln_status = tmpBkReader.getFirstText("/Transaction/Transaction_Header/SYS_TX_STATUS"); // 服务状态
//                            String xln_resp_code = tmpBkReader.getFirstText("/Transaction/Transaction_Header/SYS_RESP_CODE"); // 服务响应码
//                            String xln_resp_desc = tmpBkReader.getFirstText("/Transaction/Transaction_Header/SYS_RESP_DESC"); // 服务响应描述
//                            retAts.respCode = "0";
//
//                            if (IsResultInvlid(tmpStrRet[1], tmpBkReader, false, retAts)) {
//                                if (tmpBkReader != null) {
//                                    String tmpStatus = tmpBkReader.getFirstText("/Transaction/Transaction_Header/SYS_TX_STATUS");
//                                    String tmpCode = tmpBkReader.getFirstText("/Transaction/Transaction_Body/response/Vchr_St");
//                                    String tmpResponseStatus = tmpBkReader.getFirstText("/Transaction/Transaction_Header/tran_response/status");
//                                    if (tmpResponseStatus != null && tmpResponseStatus.equals("FAIL")) {
//                                        String tmpResponseCode = tmpBkReader.getFirstText("/Transaction/Transaction_Header/tran_response/code");
//                                        String tmpResponseDesc = tmpBkReader.getFirstText("/Transaction/Transaction_Header/tran_response/desc");
//                                        retAts.transState = tmpStatus + "+" + "FAIL" + "+" + tmpResponseCode;
//                                        retAts.payInfoCode = retAts.transState;
//                                        retAts.respInfo = "状态：" + tmpResponseStatus + ",银行状态码：" + tmpResponseCode + ",原因：" + tmpResponseDesc;
//                                    } else {
//                                        retAts.transState = tmpStatus + "+" + "submitted";
////                                    retAts.payInfoCode = tmpBkReader.getFirstText("/Transaction/Transaction_Body/response/RDsc");
//                                        retAts.payInfoCode = retAts.transState;
//                                        retAts.respInfo = tmpBkReader.getFirstText("/Transaction/Transaction_Body/response/RDsc") + ",银行状态码：" + tmpCode;
//                                    }
//                                }
//                            } else {
//                                String tmpRespInfo = tmpBkReader.getFirstText("/Transaction/Transaction_Header/tran_response/desc");
//                                if (StringHelper.isNullOrEmpty(tmpRespInfo)) {
//                                    tmpRespInfo = xln_status + xln_resp_code + xln_resp_desc;
//                                }
//                                String tmpCode = tmpBkReader.getFirstText("/Transaction/Transaction_Header/tran_response/code");
//                                retAts.respInfo = tmpRespInfo + ",错误码：" + tmpCode;
//
//                                String tmpStatus = tmpBkReader.getFirstText("/Transaction/Transaction_Header/SYS_TX_STATUS");
//                                String status = tmpBkReader.getFirstText("/Transaction/Transaction_Header/tran_response/status");
//
//                                retAts.transState = tmpStatus + "+" + status;
//                                retAts.payInfoCode = retAts.transState;
//                            }
//                        } else {
//                            retAts.respCode = "-1";
//                            retAts.respInfo = tmpStrRet[1];
//                        }
//                    } else {
//                        retAts.respCode = "-1";
//                        retAts.respInfo = "签到失败";
//                    }
//                } else {
//                    retAts.respCode = "-1";
//                    retAts.respInfo = "下载银行pub密钥失败";
//                }
//            } else {
//                retAts.respCode = "-1";
//                retAts.respInfo = "下载银行3des密钥失败";
//            }
//        } catch (Exception ex) {
//            ex.printStackTrace();
//            retAts.writeRespCode("-1");
//            retAts.writeRespInfo(ex.getMessage());
//            WriteBankLogLn(ex);
//        }
//
//        retAts.writeRetToATS();
//        return retAts;
//    }
//}
